/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.seckill.api.listener;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.OrderType;
import com.yami.shop.bean.event.CancelOrderEvent;
import com.yami.shop.bean.event.CheckSecKillOrderEvent;
import com.yami.shop.bean.order.CancelOrderOrder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.model.SeckillOrder;
import com.yami.shop.seckill.comment.service.SeckillOrderService;
import com.yami.shop.seckill.comment.service.SeckillService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 支付时校验订单过期事件
 * @author lhd
 */
@Component("checkSecKillOrderListener")
@AllArgsConstructor
public class CheckSecKillOrderListener {


    private final SeckillOrderService seckillOrderService;
    private final SeckillService seckillService;

    @EventListener(CheckSecKillOrderEvent.class)
    public void checkSecKillOrderHandle(CheckSecKillOrderEvent event) {
        String orderNumber = event.getOrder().getOrderNumber();
        SeckillOrder seckillOrder = seckillOrderService.getOne(new LambdaQueryWrapper<SeckillOrder>().eq(SeckillOrder::getOrderNumber, orderNumber));
        Seckill seckill = seckillService.getById(seckillOrder.getSeckillId());
        // 订单创建时间经过秒杀限定分钟，如果为true则早于当前时间表示过期，抛出异常
        if(!DateUtil.isExpired(seckillOrder.getCreateTime(), DateField.MINUTE, seckill.getMaxCancelTime(), new Date())){
            // 秒杀订单已经过期，无法进行支付
            throw new YamiShopBindException("yami.order.expired");
        }
    }

}
